package net.xdclass.controller;

import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.auth.ScheduledUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.WechatPayConfig;
import net.xdclass.enums.ProductOrderPayTypeEnum;
import net.xdclass.service.ProductOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Controller
@RequestMapping("/api/callback/order/v1")
@Slf4j
public class PayCallbackController {

    @Autowired
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private ScheduledUpdateCertificatesVerifier verifier;

    @Autowired
    private ProductOrderService productOrderService;

    @RequestMapping("wechat")
    @ResponseBody
    public Map<String, String> wechatPayCallback(HttpServletRequest request, HttpServletResponse response){
        //获取报文
        String body = getRequestBody(request);
        //随机串
        String nonceStr = request.getHeader("Wechatpay-Nonce");
        //微信传递过来的签名
        String signature = request.getHeader("Wechatpay-Signature");
        //证书序列号（微信平台）
        String serialNo = request.getHeader("Wechatpay-Serial");
        //时间戳
        String timestamp = request.getHeader("Wechatpay-Timestamp");

        //构造签名串
        String signStr = Stream.of(timestamp, nonceStr, body).collect(Collectors.joining("\n", "", "\n"));

        Map<String, String> map = new HashMap<>();
        try {
            //验证签名是否通过
            boolean result = verifiedSign(serialNo, signStr, signature);
            // 解密数据
            if (result) {
                String decryptBody = decryptBody(body);
                Map<String, String> paramsMap = convertWechatPayMsgToMap(decryptBody);

                //处理业务逻辑
                productOrderService.processOrderCallbackMsg(ProductOrderPayTypeEnum.WECHAT_PAY, paramsMap);


            }


            map.put("code", "SUCCESS");
            map.put("message", "成功");
        } catch (Exception e) {
            log.error("微信支付回调异常:{}", e);
        }
        return map;
    }

    private Map<String, String> convertWechatPayMsgToMap(String plainbody) {
        Map<String, String> paramsMap = new HashMap<>();
        JSONObject jsonObject = JSONObject.parseObject(plainbody);
        //商户订单号
        paramsMap.put("out_trade_no", jsonObject.getString("out_trade_no"));
        // 交易状态
        paramsMap.put("trade_state", jsonObject.getString("trade_state"));
        // 附加数据
        paramsMap.put("account_no", jsonObject.getJSONObject("attach").getString("accountNo"));
        return paramsMap;
    }

    /**
     * 解密body的密文
     * @param body
     * @return
     */
    private String decryptBody(String body) throws GeneralSecurityException {
        AesUtil aesUtil = new AesUtil(wechatPayConfig.getApiV3Key().getBytes(StandardCharsets.UTF_8));
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject resource = jsonObject.getJSONObject("resource");
        String ciphertext = resource.getString("ciphertext");
        String associatedData = resource.getString("associated_data");
        String nonce = resource.getString("nonce");
        return aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
    }

    /**
     * 验证签名
     * @param serialNo
     * @param signStr
     * @param signature
     * @return
     */
    private boolean verifiedSign(String serialNo, String signStr, String signature){
        return verifier.verify(serialNo, signStr.getBytes(StandardCharsets.UTF_8), signature);
    }


    /**
     * 读取请求数据流
     * @param request
     * @return
     */
    private String getRequestBody(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();

        try (ServletInputStream inputStream = request.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
            String line;
            while ((line=reader.readLine())!=null){
                sb.append(line);
            }
        } catch (Exception e ){
            log.error("读取数据流异常:{}", e);
        }
        return sb.toString();
    }

}
